package com.gzm.framework.security.service;

import com.gzm.framework.aop.enums.UserStatus;
import com.gzm.framework.exception.BaseException;
import com.gzm.user.system.entity.BUser;
import com.gzm.user.system.entity.vo.LoginUser;
import com.gzm.user.system.mapper.BUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 用户验证处理
 */
@Service
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private BUserMapper bUserMapper;

    @Override
    public LoginUser loadUserByUsername(String username) throws UsernameNotFoundException {
       BUser user = bUserMapper.loadUserByUsername(username);
        if (user == null) {
            log.info("登录用户：{} 不存在.", username);
            throw new BaseException("登录用户：" + username + " 不存在");
        } else if (UserStatus.DELETED.getCode().equals(user.getState())) {
            log.info("登录用户：{} 已被删除.", username);
            throw new BaseException("对不起，您的账号：" + username + " 已被删除");
        }
        return createLoginUser(user);
    }

    public LoginUser createLoginUser(BUser user) {
        return new LoginUser(user);
    }
}
